package com.gogowan.agroenterprise.newview;

import android.Manifest;
import android.app.ActionBar;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Debug;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.manager.LoadController;
import com.android.volley.manager.RequestManager;
import com.gogowan.agroenterprise.MyApplication;
import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.barcode.CaptureActivity;
import com.gogowan.agroenterprise.barcode.Intents;
import com.gogowan.agroenterprise.base.BaseActivity;
import com.gogowan.agroenterprise.contorl.MsgType;
import com.gogowan.agroenterprise.model.CheckRecordRequest;
import com.gogowan.agroenterprise.model.CheckRecordResult;
import com.gogowan.agroenterprise.model.CheckScanRequest;
import com.gogowan.agroenterprise.model.CheckScanResult;
import com.gogowan.agroenterprise.model.MarketRecode;
import com.gogowan.agroenterprise.model.UserType;
import com.gogowan.agroenterprise.utils.DatePickerWindow;
import com.gogowan.agroenterprise.utils.PopupWindowUtil;
import com.gogowan.agroenterprise.utils.ToastUtils;
import com.gogowan.agroenterprise.utils.Util;
import com.gogowan.agroenterprise.utils.Utils;
import com.gogowan.agroenterprise.widget.MyProgressDialog;
import com.gogowan.agroenterprise.widget.adapter.MainListViewAdapater;
import com.ioid.utils.JsonUtils;
import com.liaoinstan.springview.container.DefaultHeader;
import com.liaoinstan.springview.widget.SpringView;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 主界面
 *
 * @author tjh 2016-08-11
 */
public class JiChaActivity extends BaseActivity implements View.OnClickListener, RequestManager.RequestListener {

    private static final int ORDER_NO_SCAN = 101;
    private static final int ORDER_DETAIL_SCAN = 102;
    // 判读退出时间间隔
    private long exitTime = 0;
    private MyProgressDialog progressDialog;
    private LoadController mLoadController = null;
    private int checkRecordRequestCode =10124;
    private int CheckhttpRequestCode =10125;
    private ListView listView;
    private SpringView springView;
    private TextView startTime_Tv,endTime_Tv;
    private PopupWindowUtil SelectTimeutil;
    private int selectTimeType=0;
    private String StartTimeStr,EndTimeStr;
    private MainListViewAdapater adapater;
    private List<MarketRecode> marketRecodeList=new ArrayList<>();
    private int page=1;
    private String resultString;
//    private LoginResultInfo info;
    private RadioButton NullRbt,PublicRb;
    private static int MY_PERMISSIONS_CAMERA=9031;
    private CheckRecordResult recordResult;
    private int usertype;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jicha);
        usertype = MyApplication.mSettings.getInt("usertype", UserType._GONG_CHANG.getTypeID());
        initView();
    }
    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();

    }
    /**
     * 初始化界面
     */
    private void initView() {
        SelectTimeutil=new PopupWindowUtil(this);
        progressDialog = new MyProgressDialog(this, "");
        listView=(ListView)findViewById(R.id.mainlist);
        springView=(SpringView)findViewById(R.id.main_Sv);
        StartTimeStr="";
        EndTimeStr="";
        springView.setFooter(new DefaultHeader(this));
        springView.setHeader(new DefaultHeader(this));
        springView.setListener(new SpringView.OnFreshListener() {
            @Override
            public void onRefresh() {
                page=1;
                http(page);
            }

            @Override
            public void onLoadmore() {
                if (recordResult!=null){
                    page++;
                    if (recordResult.getTotalPage()>=page){
                        http(page);
                    }else {
                        springView.onFinishFreshAndLoad();
                        showToast("没有更多数据了");
                    }
                }
            }
        });
//        info=(LoginResultInfo)getIntent().getSerializableExtra("loginResult");
        http(page);
//        PeoplePopupWindo();
        selectTimeWindo();
    }
    @Override
    public void onClick(View v) {
        if (Utils.isDClick()) {
            return;
        }
        switch (v.getId()) {
            case R.id.my_Tv:
                PopupWindoDismiss();
                break;
            case R.id.peopleIv:
                finish();
                break;
            case R.id.peopleback_LL:
                PopupWindoDismiss();
                break;
            case R.id.time_select_cancle_Tv:
                PopupWindoDismiss();
                break;
            case R.id.modify_pwd_Tv:
                PopupWindoDismiss();
                modefiypwd();
                break;
            case R.id.main_scan_btn:
                getCameraPerisson();
                break;
            case R.id.main_sx_btn:
                SelectTimeutil.show(Gravity.BOTTOM,0,0);
                break;
            case R.id.select_time_two_Rb:
                ModifyRbTextColor(v);
                selectTimeType= 1;
                StartAndEndTimeHint();
                break;
            case R.id.select_time_seven_Rb:
                ModifyRbTextColor(v);
                selectTimeType= 2;
                StartAndEndTimeHint();
                break;
            case R.id.select_time_one_Rb:
                ModifyRbTextColor(v);
                selectTimeType= 3;
                StartAndEndTimeHint();
                break;
            case R.id.select_time_three_Rb:
                ModifyRbTextColor(v);
                selectTimeType= 4;
                StartAndEndTimeHint();
                break;
            case R.id.select_time_startTime_Tv:
                ModifyRbTextColor(v);
                DatePickerWindow.init(this,startTime_Tv).StartTime(endTime_Tv.getText().toString());
                SelectTimeRbHint();
                break;
            case R.id.select_time_endTime_Tv:
                ModifyRbTextColor(v);
                DatePickerWindow.init(this,endTime_Tv).EndTime(startTime_Tv.getText().toString());
                SelectTimeRbHint();
                break;
            case R.id.time_select_search_Tv:
                StartTimeStr=startTime_Tv.getText().toString();
                EndTimeStr=endTime_Tv.getText().toString();
                if(StartTimeStr.length()>0|| EndTimeStr.length()>0){
                    if (StartTimeStr.length()<1){
                        showToast("请选择开始时间");
                        return;
                    }
                    if(EndTimeStr.length()<1){
                        showToast("请选择结束时间时间");
                        return;
                    }
                    if (!Utils.isDateOneBigger(StartTimeStr,EndTimeStr)){
                        showToast("结束时间不能小于开始时间");
                        return;
                    }
                }
                PopupWindoDismiss();
                http(1);
                break;
        }
    }

    private void ModifyRbTextColor(View v) {
        if (PublicRb!=null){
            PublicRb.setTextColor(getResources().getColor(R.color.font_black));
            PublicRb=null;
        }
        try {
            PublicRb =(RadioButton)SelectTimeutil.getView().findViewById(v.getId());
            PublicRb.setTextColor(getResources().getColor(R.color.white));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void PopupWindoDismiss(){
//        util.getPopupWindow().dismiss();;
        SelectTimeutil.getPopupWindow().dismiss();
    }
    /**
     * 重置检索时间
     */
    private void StartAndEndTimeHint(){
        startTime_Tv.setText("");
        endTime_Tv.setText("");
        StartTimeStr="";
        EndTimeStr="";
    }
    /**
     * 重置检索区间
     */
    private void SelectTimeRbHint(){
        selectTimeType=0;
        NullRbt.performClick();
    }
    /**
     * 右上角弹出窗口
     */
    private void selectTimeWindo(){
        SelectTimeutil.setContextView(R.layout.select_date_layout).setType( ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.MATCH_PARENT);
        SelectTimeutil.getView().findViewById(R.id.windowLL).setOnClickListener(this);
        SelectTimeutil.getView().findViewById(R.id.select_time_two_Rb).setOnClickListener(this);
        SelectTimeutil.getView().findViewById(R.id.select_time_seven_Rb).setOnClickListener(this);
        SelectTimeutil.getView().findViewById(R.id.select_time_one_Rb).setOnClickListener(this);
        SelectTimeutil.getView().findViewById(R.id.select_time_three_Rb).setOnClickListener(this);
        NullRbt=(RadioButton)SelectTimeutil.getView().findViewById(R.id.select_null_rb);
        SelectTimeutil.getView().findViewById(R.id.time_select_search_Tv).setOnClickListener(this);
        SelectTimeutil.getView().findViewById(R.id.peopleback_LL).setOnClickListener(this);
        SelectTimeutil.getView().findViewById(R.id.time_select_cancle_Tv).setOnClickListener(this);
        startTime_Tv=(TextView)SelectTimeutil.getView().findViewById(R.id.select_time_startTime_Tv);
        endTime_Tv=(TextView)SelectTimeutil.getView().findViewById(R.id.select_time_endTime_Tv);
        startTime_Tv.setOnClickListener(this);
        endTime_Tv.setOnClickListener(this);
//        startTime_Tv.setText(Utils.getTime());
//        endTime_Tv.setText(Utils.getTime());
        StartTimeStr="";
        EndTimeStr="";
        selectTimeType=0;
    }
    /**
     * 网络请求
     */
    private void http(int Ys){
        progressDialog.setCancelable(false);
        progressDialog.setLoadingText("正在查询" + "\n"
                + getString(R.string.prompt_progress_wait));
        progressDialog.show();
        CheckRecordRequest checkRecordRequest=new CheckRecordRequest();
        checkRecordRequest.setStime(StartTimeStr);
        checkRecordRequest.setEtime(EndTimeStr);
        checkRecordRequest.setTimetype(selectTimeType);
        if(usertype==UserType._JING_XIAO_SHANG.getTypeID()){
            long userId = MyApplication.mSettings.getLong("personid", 0);
            checkRecordRequest.setCreateBy(userId+"");
        }
        checkRecordRequest.setPageIndex(Ys);
        checkRecordRequest.setUserId(MyApplication.mSettings.getLong("personid",0)+"");
        String messageStr = Utils.getPostRequest(checkRecordRequest, MsgType.Temp.CheckRecord.getValue());
        Map<String,String>map=new HashMap<>();
        map.put("X-Access-Token", MyApplication.mSettings.getString("token",""));
        mLoadController=RequestManager.getInstance().request(Request.Method.POST,
                getString(R.string.first_url)+getString(R.string.listApp),
                messageStr,map, this,false,
                600*1000, 1, checkRecordRequestCode);
    }
    /**
     * 修改密码
     */
    private void modefiypwd(){
//        Intent intent = new Intent(this, ModifyPasswordActivity.class);
//        intent.putExtra("UserInfo",info.getUserinfo());
//        startActivity(intent);
    }
    private void setlistView(List<MarketRecode> list){
        if (list!=null){
            if (page==1){
                marketRecodeList=list;
                adapater=new MainListViewAdapater(this,marketRecodeList);
                listView.setAdapter(adapater);
            }else {
                marketRecodeList.addAll(list);
                adapater.notifyDataSetChanged();
            }
        }

    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (resultCode == RESULT_OK) {
            if (requestCode == ORDER_NO_SCAN) {
                //出库单号
                resultString = intent
                        .getStringExtra(Intents.Scan.RESULT);
                progressDialog.setCancelable(false);
                progressDialog.setLoadingText("正在提交请求" + "\n"
                        + getString(R.string.prompt_progress_wait));
                progressDialog.show();
                if(resultString.contains("=")){
                    resultString=resultString.substring(resultString.indexOf("=")+1,resultString.length());
                }
                CheckScanRequest request=new CheckScanRequest();
                long personid = MyApplication.mSettings.getLong("personid", 0);
                request.setEnterpriseId(personid+"");
                request.setProductCode(resultString);
                String messageStr = Utils.getPostRequest(request, MsgType.Temp.CheckScan.getValue());
                Map<String,String>map=new HashMap<>();
                map.put("X-Access-Token", MyApplication.mSettings.getString("token",""));
                mLoadController = RequestManager.getInstance().request(Request.Method.POST,
                        getString(R.string.first_url)+getString(R.string.getSaleRecordAPP),
                        messageStr, map,this,false,
                        600*1000, 1,CheckhttpRequestCode);
            }
        }
        if (resultCode==Utils.save_Result_Code){
            springView.callFresh();
        }
    }
    @Override
    public void onRequest() {

    }
    @Override
    public void onSuccess(String response, Map<String, String> headers, String url, int actionId) {
        progressDialog.dismiss();

        if (actionId == checkRecordRequestCode) {
            try {
                JSONObject jo=new JSONObject(response);
                if(jo.getInt("code")!=200){
                    ToastUtils.show(getApplicationContext(),jo.getString("msg"));
                    return;
                }
                response=jo.getJSONObject("data").toString();

            }catch (Exception e){
                e.printStackTrace();
                ToastUtils.show(getApplicationContext(),"数据解析失败");
            }
            recordResult=(CheckRecordResult) JsonUtils.fromJSON(response,
                    CheckRecordResult.class);

            springView.onFinishFreshAndLoad();
            if (recordResult!=null){
                findViewById(R.id.notList_Tv).setVisibility(View.GONE);
                springView.setVisibility(View.VISIBLE);
                setlistView(recordResult.getList());
            }else {
                showToast("暂无数据");
            }
        }else if (actionId==CheckhttpRequestCode){
            String msg="";
            try {
                JSONObject jo=new JSONObject(response);
                if(jo.getInt("code")!=200){
                    ToastUtils.show(getApplicationContext(),jo.getString("msg"));
                    return;
                }
                response=jo.getJSONObject("data").toString();
                msg=jo.getString("msg");
            }catch (Exception e){
                e.printStackTrace();
                ToastUtils.show(getApplicationContext(),"数据解析失败");
            }
            CheckScanResult checkScanResult=(CheckScanResult)JsonUtils.fromJSON(response,CheckScanResult.class);
            checkScanResult.setResultinfo(msg);
            if (checkScanResult!=null){
                Intent intent=new Intent(JiChaActivity.this,Commodity_Inspection_Activity.class);
                intent.putExtra("resultString",resultString);
                intent.putExtra("CheckScanResult",checkScanResult);
//                    intent.putExtra("info",info);
                startActivityForResult(intent,Utils.save_Result_Code);

            }else {
                showToast("数据异常");
            }
        }
    }
    @Override
    public void onError(String errorMsg, String url, int actionId) {
        progressDialog.cancel();
        switch (actionId) {
            case ORDER_NO_SCAN:
                ShowDialog("提示", getString(R.string.prompt_internet_fail));
                break;
        }
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {

            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序",
                        Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLoadController != null) {
            mLoadController.cancel();
            mLoadController = null;
        }
        if (progressDialog != null) {
            progressDialog.cancel();
            progressDialog = null;
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        getCameraPerisson();
    }
    /**
     * 获取摄像头权限
     */
    public void getCameraPerisson() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            new AlertDialog.Builder(this).setTitle("提示").setMessage("请同意摄像机权限，否则将无法应用扫描功能").setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    ActivityCompat.requestPermissions(JiChaActivity.this, new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_CAMERA);
                }
            }).show();
        }else {
            if(Debug.isDebuggerConnected()){
                resultString ="MA.156.M0.100366.0c0116727025.S0133024.M230320.L20230357.V260319.C3";
                progressDialog.setCancelable(false);
                progressDialog.setLoadingText("正在提交请求" + "\n"
                        + getString(R.string.prompt_progress_wait));
                progressDialog.show();
                if(resultString.contains("=")){
                    resultString=resultString.substring(resultString.indexOf("=")+1,resultString.length());
                }
                CheckScanRequest request=new CheckScanRequest();
                long personid = MyApplication.mSettings.getLong("personid", 0);
                request.setEnterpriseId(personid+"");
                request.setProductCode(resultString);
                String messageStr = Utils.getPostRequest(request, MsgType.Temp.CheckScan.getValue());
                Map<String,String>map=new HashMap<>();
                map.put("X-Access-Token", MyApplication.mSettings.getString("token",""));
                mLoadController = RequestManager.getInstance().request(Request.Method.POST,getString(R.string.first_url)+getString(R.string.getSaleRecordAPP),
                        messageStr, map,this,false,600*1000, 1,CheckhttpRequestCode);
                return;
            }
            Intent intent = new Intent(Intents.Scan.ACTION);
            CaptureActivity.ISBULKMODE = false;
            intent.putExtra(Util.Intent.CAPTURE_TITLE, "二维码扫描");
            this.startActivityForResult(intent, ORDER_NO_SCAN);
        }
    }
}
